<?php
namespace common\models\redPacket;

use common\models\Common;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\user\User;
use common\models\userFund\UserMoneyLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class RedPacketLog extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%red_packet_log}}';
    }

    public function getReceiveUser()
    {
        return $this->hasOne(User::className(), ['id' => 'receive_user_id']);
    }

    public function getSendUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    // 退回过期红包
    public function backRedPacket() {
        return false;
        $redis = Yii::$app->redis;
        $trans = static::getDb()->beginTransaction();
        try {

            $where = $andWhere = [];
            $andWhere[] = ['<=','create_time',date('Y-m-d H:i:s',strtotime("-1 days"))];
            $where['status'] = Status::RED_PACKET_WAIT;
            $redPacketLogList = static::getObjectByAndWhere($where,$andWhere,['SUM(receive_money) as totalReceiveMoney','id','create_time','status','red_packet_id','user_id','user_tx_code'])
                ->with()->groupBy('red_packet_id')->having(['>','totalReceiveMoney',0])->asArray()->all();

            if ($redPacketLogList) {
                $userMoneyLogModel = new UserMoneyLog();
                $redPacketModel = new RedPacketLog();
                $imModel = new Im();
                $config = static::getCommonByKey('money_user_id');
                foreach ($redPacketLogList as $kk => $vv) {
                    // 余额信息
                    $userMoneyLogModel::record(
                        $vv['user_id'],
                        Status::PROP_TYPE_MONEY,
                        Status::MONEY_LOG_TYPE_BACK_RED_PACKET,
                        abs($vv['totalReceiveMoney']),
                        Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BACK_RED_PACKET] ?? '',
                        '红包撤回',
                        $vv['red_packet_id']
                    );

                    $updateData['status'] = Status::RED_PACKET_RETURN;
                    static::updateData($updateData,[
                        'red_packet_id' => $vv['red_packet_id'],
                        'status' => Status::RED_PACKET_WAIT,
                    ]);

                    # 红包已过期
                    $redPacketModel::updateData(['status' => Status::RED_PACKET_RETURN],[
                        'id' => $vv['red_packet_id'],
                        'status' => Status::RED_PACKET_WAIT,
                    ]);

                    // 发送IM信息
                    $userMessage = [];
                    $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
                    $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
                    $userMessage['title'] = "红包撤回";
                    $userMessage['money_title'] = "撤回金额";
                    $userMessage['money'] = (string) abs($vv['totalReceiveMoney']);
                    $userMessage['desc'] = "撤回".$userMessage['money']."元";
                    $userMessage['mark'] = "你可以在钱包中查看相关记录";
                    $userMessage['time'] = date('Y-m-d H:i:s');

                    $imModel -> sendUserMessage($vv['user_tx_code'], $userMessage, $config);
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '退回成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }

    public function sendMoneyMessage() {
        $imModel = new Im();
        $config = static::getCommonByKey('money_user_id');
        // 发送IM信息
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_MONEY_MESSAGE;
        $userMessage['title'] = "红包撤回";
        $userMessage['money_title'] = "撤回金额";
        $userMessage['money'] = (string) '123';
        $userMessage['desc'] = "撤回".$userMessage['money']."元";
        $userMessage['mark'] = "你可以在钱包中查看相关记录";
        $userMessage['time'] = date('Y-m-d H:i:s');

        $imModel -> sendUserMessage("549766848556524", $userMessage, $config);
    }


    /**
     *
     * 删除七天之前的红包记录 收入明细   红包信息
     * @return array
     */
    public function delLog() {
        $db = static::getDb();
        // 1.收入明细
        $endTime = date('Y-m-d H:i:s',strtotime('-10 days'));

        $sql = "delete from jq_user_money_log where change_time < '{$endTime}'";
        $db->createCommand($sql)->execute();

        //2.红包信息
        $endTime = date('Y-m-d H:i:s',strtotime('-10 days'));
        $sql1 = "delete from jq_red_packet where create_time < '{$endTime}'";
        $db->createCommand($sql1)->execute();

        //3.红包记录
        $endTime = date('Y-m-d H:i:s',strtotime('-10 days'));

        $sql2 = "delete from jq_red_packet_log where create_time < '{$endTime}'";
        $db->createCommand($sql2)->execute();

        //4.转账
        $endTime = date('Y-m-d H:i:s',strtotime('-10 days'));

        $sql3 = "delete from jq_transfer_info where create_time < '{$endTime}'";
        $db->createCommand($sql3)->execute();
    }

}